package com.gitee.srurl.oid.store;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.gitee.srurl.oid.domain.OidStoreData;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.nio.charset.StandardCharsets;

/**
 * oid的默认存储实现
 * 使用本地文件 一般项目是够用的
 * todo 后续添加buffer缓存 避免突刺现象
 *
 * @author zxw
 * @date 2023/5/7 18:08
 */
@Slf4j
public class FileOidStore implements IOidStore {

    private static final String propertiesPath = System.getProperty("java.io.tmpdir") + "short-url/oid/oid_store_{}.properties";

    @Override
    public OidStoreData readCurrentData(long workerId) {

        File file = new File(StrUtil.format(propertiesPath, workerId));
        if (!file.exists()) {
            return null;
        }

        String str = StrUtil.str(FileUtil.readBytes(file), StandardCharsets.UTF_8);
        if (StrUtil.isBlank(str)) {
            return null;
        }

        String currentIdStr = StrUtil.replace(str, "sequence=", "");
        long currentId = Long.parseLong(currentIdStr);

        return OidStoreData.builder()
                .storeSequence(currentId)
                .workerId(workerId)
                .build();
    }

    @Override
    public void saveData(long workerId, OidStoreData oidStoreData) {

        Long sequence = oidStoreData.getStoreSequence();
        if (sequence == null) {
            log.error("写入文件序列号为空.");
            throw new NullPointerException("写入序列号为空！");
        }

        String storePath = StrUtil.format(propertiesPath, workerId);
        File file = new File(storePath);
        if (!file.getParentFile().exists()) {
            FileUtil.mkParentDirs(storePath);
        }
        if (!file.exists()) {
            FileUtil.touch(file);
        }
        FileUtil.writeBytes(("sequence=" + sequence).getBytes(StandardCharsets.UTF_8), file);
    }

    @Override
    public String type() {
        return "file";
    }
}
